<template>
  <div>
    <div class="home">
      <Header :accountShow="accountShow"></Header>
      <Main></Main>
      <Footer v-if="level.hasOwnProperty('HK')"></Footer>
    </div>
    <div v-if="step == 0 && this.$route.path == '/accountCenter'" class="tipContent tipPosition1">
      <div class="title">{{$t('views.Home.56hpa36keog0')}}</div>
      <div class="content">
        {{$t('views.Home.56hpa36w3oc0')}}
      </div>
      <div class="tipButton_first">
        <!-- <div class="ban">{{$t('views.Home.56hpa36w4rs0')}}</div> -->
        <div class="first_next" @click="postGuideStep(1,true)">{{$t('views.Home.56hpa36w55w0')}}</div>
      </div>
    </div>
    <div v-if="step == 1 && this.$route.path == '/accountCenter'" class="tipContent tipPosition2">
      <div class="title">{{$t('views.Home.56hpa36w5n40')}}</div>
      <div class="content">
        {{$t('views.Home.56hpa36w68c0')}}
      </div>
      <div class="tipButton">
        <div @click="postGuideStep(0,false)">{{$t('views.Home.56hpa36w4rs0')}}</div>
        <div @click="postGuideStep(2,true)">{{$t('views.Home.56hpa36w55w0')}}</div>
      </div>
    </div>
    <div v-if="step == 2 && this.$route.path == '/quotationCenter'" class="tipContent tipPosition3">
      <div class="title">{{$t('views.Home.56hpa36w7e40')}}</div>
      <div class="content">{{$t('views.Home.56hpa36w7r00')}}</div>
      <div class="tipButton">
        <div @click="postGuideStep(1,false)">{{$t('views.Home.56hpa36w4rs0')}}</div>
        <div @click="postGuideStep(3,true)">{{$t('views.Home.56hpa36wc5w0')}}</div>
      </div>
    </div>
      <WebSocket v-if="wsDapanList.length > 0"></WebSocket>
  </div>
</template>

<script>
// @ is an alias to /src
import {get_details} from '@/assets/js/API/market.js';
import {post_guide_step, get_guide_step, get_history} from '@/assets/js/API/user.js';
import {get_finance_question} from '@/assets/js/API/market.js';
import {get_optional, getAccountStatus} from '@/assets/js/API/user.js';
import WebSocket from "../components/websocket.vue";
import Header from "./inc/header.vue";
import Footer from "./inc/footer.vue";
import Main from "./inc/main.vue";
export default {
  components: {
    Header,
    Footer,
    Main,
    WebSocket
  },
  inject: ["reload"],
  data: function () {
    return {
      accountShow: true,
      siteShow: false,
      siteKey: 0,
      siteList: [this.$i18n.t("m.General_set"), this.$i18n.t("m.System_set")],
      cgsite: {
        lang: "zh-CN",
        upDown: "",
      },
      key: 0,
      relief: "",
      historyList: [], // 搜索历史列表
      Details_data: this.$store.state.index.StockData,
      tipVisible: true, // 提示信息展示
      nextTip: 1, // 提示步骤
      tradeWSList: [], // 交易ws列表数据
      step: 99, // 引导教程步骤
    };
  },
  computed: {
    StockData() {
      return this.$store.state.index.StockData;
    },
    level() {
      return this.$store.state.index.level;
    },
    hkActive() {
      return this.$store.state.index.hkActive;
    },
    shActive() {
      return this.$store.state.index.shActive;
    },
    usActive() {
      return this.$store.state.index.usActive;
    },
    zixuanActive() {
      return this.$store.state.index.zixuanActive;
    },
    ObserveStrock() {
      return this.$store.state.index.ObserveStrock;
    },
    wsDapanList() {
      // 订阅的大盘请求
      return this.$store.state.wsModel.wsDapanList;
    },
    zixuanSub() {
      // 订阅的大盘请求
      return this.$store.state.wsModel.zixuanSub;
    }
  },
  watch: {
    StockData: {
      handler(val) {
        var _this = this;
        // 如果已经订阅过，切换股票取消不需要的订阅
        if (val !== "") {
          _this.Details_data = val;
          _this.getDetail(_this.Details_data);
        }
        _this.$forceUpdate();
      },
      deep: true,
    },
    $route(to, from) {
      // 跳转其他页面时关闭右侧抽屉
      if(from.name.slice(0, 3) == "sh_") {
        if(to.name.slice(0, 3) != "sh_") {
          this.$store.dispatch("SetShActive", false)
        }
      }else if(from.name.slice(0, 3) == "hk_") {
        if(to.name.slice(0, 3) != "hk_") {
          this.$store.dispatch("SetHkActive", false)
        }
      }else if(from.name.slice(0, 3) == "us_") {
        if(to.name.slice(0, 3) != "us_") {
          this.$store.dispatch("SetUsActive", false)
        }
      }else if(from.name == "optional") {
        if(to.name != "optional") {
          this.$store.dispatch("SetZixuanActive", false)
        }
      }
      // 跳转行情中心或个人中心时右侧抽屉为原值
      if(from.name !== "quotationCenter" || from.name !== "accountCenter"){
        if(to.name == "quotationCenter" || to.name == "accountCenter") {
          if(Object.keys(this.ObserveStrock).length > 0)
          this.$store.dispatch("SetStockData", this.ObserveStrock)
        }
      }
    },
  },
  created() {
    this.cgsite.upDown = sessionStorage.getItem("color");
    this.getGuideStep();
  },
  mounted() {
    this.$nextTick(() => {
      this.cgsite.lang = localStorage.getItem("lang");
      this.$i18n.locale = localStorage.getItem("lang");
      document.getElementsByTagName(
        "body"
      )[0].className = sessionStorage.getItem("color");
      this.getHistory();
    });
  },
  beforeDestroy() {
    if(this.heartbeat) {
      // 退出时断开ws
      this.heartbeat.close();
    }
  },
  methods: {
    // 切换语言
    selectLang() {
      localStorage.setItem("lang", this.cgsite.lang);
      this.$i18n.locale = this.cgsite.lang;
      this.$i18n.locale = localStorage.getItem("lang");
      this.reload();
    },
    // 切换红涨绿跌颜色
    selectColor(val) {
      this.$confirm(
        this.$i18n.t("m.operation_will"),
        this.$i18n.t("m.prompt"),
        {
          confirmButtonText: this.$i18n.t("m.determine"),
          cancelButtonText: this.$i18n.t("m.cancel"),
          type: "warning",
        }
      )
        .then(() => {
          this.$message({
            type: "success",
            message: this.$i18n.t("m.Success_switched"),
          });
          this.cgsite.upDown = val;
          if (val == "") {
            sessionStorage.removeItem("color");
          } else {
            sessionStorage.setItem("color", val);
          }
          document.getElementsByTagName("body")[0].className = val;
          this.siteShow = false;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$i18n.t("m.CancelledSwitch"),
          });
          // this.cgsite.upDown = val=='theme'?'':'theme';
        });
    },
    // 自选股列表
    zixuans() {
      let _this = this;
      _this.loading = true;
      if (_this.loading) {
          get_optional(_this.optionSubmit).then(function (res) {
            if (res.code == 1) {
              _this.tableList = res.data.list;
              _this.tableList.forEach(function (res) {
                res.latestPrice = parseFloat(res.latestPrice);
                res.gain = parseFloat(res.gain);
              });
              let wsList = _this.addWsList(_this.tableList);
              _this.$store.dispatch("SetZixuanSub", JSON.stringify(wsList));
              _this.loading = false;
            } else {
              _this.$message({
                message: res.msg,
                type: "warning",
              });
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    },
    // 将自选股添加进自选订阅队列
    addWsList(list) {
      let wsList = [];
      list.forEach((item) => {
        let objs = {};
        if(item.market == "SZSE" || item.market == "SSE") {
          // 自选股票为沪深，且等级为2时放入推送
          if(this.level.CN && this.level.CN.level) {
            if(this.level.CN.level == 2) {
              this.$set(objs, "market", item.market);
              this.$set(objs, "securityType", item.securityType);
              this.$set(objs, "action", "Q");
              this.$set(objs, "symbol", item.symbol);
              wsList.push(objs);
            }
          }
        }else if (item.market == "HKEX") {
          // 自选股票为港股，且等级为2时放入推送
          if(this.level.HK && this.level.HK.level) {
            if(this.level.HK.level == 2) {
              this.$set(objs, "market", item.market);
              this.$set(objs, "securityType", item.securityType);
              this.$set(objs, "action", "Q");
              this.$set(objs, "symbol", item.symbol);
              wsList.push(objs);
            }
          }
        }else if(item.market == "US") {
          // 自选股票为美股，且等级为1时放入推送
          if(this.level.US && this.level.US.level) {
            if(this.level.US.level == 1) {
              this.$set(objs, "market", item.market);
              this.$set(objs, "securityType", item.securityType);
              this.$set(objs, "action", "Q");
              this.$set(objs, "symbol", item.symbol);
              wsList.push(objs);
            }
          }
        }
      });
      console.log(list, wsList, this.$t('views.Home.56hpa36w9tc0'));
      return wsList;
    },
    // 获取历史股票列表
    async getHistory() {
      const res = await get_history();
      if (res.code != 1) return this.$message.error(res.msg);
      this.historyList = res.data.list;

      // 如果是没有历史搜索，默认展示腾讯股票
      if (this.historyList.length !== 0) {
        var obj = {
          securityType: res.data.list[0].securityType,
          symbol: res.data.list[0].symbol,
          market: res.data.list[0].market,
        };
      } else {
        var obj = {
          securityType: 1,
          symbol: "00700",
          market: "HKEX",
        };
      }
      this.$store.dispatch("SetStockData", obj);
    },
    // 获取历史股票中第一支股票的详情
    async getDetail(item) {
      const res = await get_details({
          market: item.market,
          symbol: item.symbol,
          securityType: item.securityType,
        });
      if (res.code != 1) return this.$message.error(res.msg);
      this.$store.dispatch("SetStock", res.data);
      // this.$store.dispatch("SetStockData", res.data);
      if (
        res.data.detail.isSupportFinance != false ||
        res.data.detail.isSupportShort != false
      ) {
        this.getFinanceQuestion(item);
      }
    },
    // 获取融资融券信息
    async getFinanceQuestion(item) {
      const res = await get_finance_question({
          market: item.market,
          symbol: item.symbol,
          securityType: item.securityType,
        });
      if (res.code != 1) return this.$message.error(res.msg);
      this.$store.dispatch("SetFinanceQuestion", res.data);
    },
    // 获取新手导航步骤
    async getGuideStep() {
      const res = await get_guide_step();
      if(res.code != 1) return this.$message.error(res.msg);
      this.step = res.data.step;
      if(this.step == 0 || this.step == 1) {
        this.$router.push({ path: "/accountCenter" });
      }
      else if(this.step == 2) {
        this.$router.push({ path: "/quotationCenter" });
      }
    },
    // 提交引导步骤请求
    async postGuideStep(index,isForward) {
      const res = await post_guide_step({
        step: index
      });
      if(res.code != 1) return this.$message.error(res.msg);
      if(isForward == true) {
        if(index == 2)
        this.$router.push({ path: "/quotationCenter" });
        this.step++;
      }else {
        // 后退
        if(index == 1)
        this.$router.push({ path: "/accountCenter" });
        this.step--;
      }
    },
  },
};
</script>
<style lang="less" scoped>
.home {
  display: flex;
  flex-direction: column;
  background-color: @deepBg;
  height: 100vh;
}
.tipContent {
  position: absolute;
  background-color: @hoverColor;
  color: @fff;
  font-size: 14px;
  z-index: 100;
  border-radius: 3px;
  padding: 8px 12px;
  box-sizing: border-box;
  // height: 140px;
  width: 332px;
  .content {
    font-size: 12px;
    border-bottom: 1px solid @fff;
    padding-bottom: 12px;
  }
  .tipButton {
    display: flex;
    font-size: 12px;
    align-items: center;
    justify-content: space-between;
    padding-top: 5px;
    cursor: pointer;
    .ban {
      cursor: not-allowed;
    }
  }
  .tipButton_first {
    display: flex;
    font-size: 12px;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  &::before {
    content: "";
    position: absolute;
    width: 0;
    height: 0;
    border: 8px solid transparent;
    border-bottom-color: @hoverColor;
    top: -16px;
    right: 30px;
  }
}
.tipPosition1 {
  top: 45px;
  right: 160px;
}
.tipPosition2 {
  top: 100px;
  right: 0;
}
.tipPosition3 {
  top: 90px;
  right: 440px;
}
@media screen and (max-width: 1442px) {
}
</style>